package com.jzt.gateway.collect;

import com.jzt.gateway.GlobalConstant;
import com.jzt.gateway.dto.request.LoginNamePassword;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

/**
 * 作者：lizw <br/>
 * 创建时间：2020/07/03 15:43 <br/>
 */
@Component
@Slf4j
public class ZytCollectLoginData extends AbstractCollectLoginData {

    @Override
    public int order() {
        return Integer.MAX_VALUE - 1;
    }

    @Override
    public boolean support(ServerWebExchange exchange) {
        String body = exchange.getAttribute(GlobalConstant.CACHED_REQUEST_BODY_STR_ATTR);
        JSONObject jsonBody = new JSONObject(body);
        LoginNamePassword login;
        try {
            login = getLoginNamePassword(exchange, jsonBody);
        } catch (Exception e) {
            return false;
        }
        return login != null && StringUtils.isNotBlank(login.getName()) && StringUtils.isNotBlank(login.getPassword());
    }

    /**
     * 获取用户名密码登录信息
     */
    @Override
    protected LoginNamePassword getLoginNamePassword(ServerWebExchange exchange, JSONObject jsonBody) {
        final String nameParamName = "username";
        final String passwordParamName = "password";
        String name = jsonBody.has(nameParamName) ? jsonBody.getString(nameParamName) : null;
        String password = jsonBody.has(passwordParamName) ? jsonBody.getString(passwordParamName) : null;
        LoginNamePassword loginNamePassword = new LoginNamePassword();
        loginNamePassword.setName(name);
        loginNamePassword.setPassword(password);
        return loginNamePassword;
    }
}
